package controller

import (
	"net/http"

	"alolang.org.cn/api/server/log"
	"alolang.org.cn/api/server/model"
	"github.com/gin-gonic/gin"
)

// CheckLogin 检查是否登录
func CheckLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		authToken := c.Request.Header.Get("Authorization")
		if authToken == "" {
			log.Logger.Infof("authToken not found")
			c.String(http.StatusUnauthorized, "Not Authorized")
			c.Abort()
			return
		}
		// TODO: Deal with JWT Bearer Token
		// c.Set(AuthedUserKey, user)
		j := model.NewJWT()
		claims, err := j.ParseToken(authToken)
		if err != nil {
			c.String(http.StatusUnauthorized, err.Error())
			c.Abort()
			return
		}
		c.Set("claims", claims)
	}
}

// IsAdmin 检查是否是管理员
func IsAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims := c.MustGet("claims").(*model.UserClaims)
		user, _ := model.GetUserByID(claims.UserID)
		if user.Role != 1 {
			c.String(http.StatusUnauthorized, "You are not admin")
			c.Abort()
			return
		}
	}
}
